<?php
require 'HTTPSocket.php';

class baseAPIClass{
	public static function debug($value){
		echo "<pre>";
		print_r($value);
		echo "</pre>";
	}
}

class httpapi extends baseAPIClass{
	public static $debug=false;
	
	private static function handle_first_line($line){
		$tokens = explode(" ",$line);
		$status=array(
			"protocol"=>$tokens[0],
//			"code"=>intval($tokens[1]),
//			"code"=>intval($tokens[1]),
			"code"=>$tokens[1],			
			"flag"=>$tokens[2]
		);
		
		return $status;
	}

	private static function processRespone($response){
		
		$http_response=array(
			"status" => array(),
			"headers" => array(),
			"body" => ""
		);
		
		$first=true;
		$start_body=false;
		$body="";
		
		$last_item = end($response);
		foreach ( $response as $line ) {
		//	httpapi::debug('<p>'.$line.'</p>');
			if($first==true){
				$t=httpapi::handle_first_line($line);
				$http_response['status']=$t;
				$first=false;
			}else{
				if($start_body==true){
					$body.=$line;
				}else{
					$line=str_replace("\n","",$line);
					$line=str_replace("\r","",$line);
					
					if(strlen($line)!=0){
						$pattern = '/^([a-z0-9A-Z\-]{1,}):/';
						preg_match($pattern, $line, $matches);
						$value=str_replace($matches[0],"",$line);
						$key=substr($matches[0], 0, -1);

						$http_response['headers'][$key]=$value;						
					}else{
						$start_body=true;
					}
				}
			}
		}
		
		$http_response['body']=$body;
		// httpapi::debug($http_response);
		return $http_response;
	}
	
	public static function makeGetRequest($options,$params=array(),$headers=array()){
		// httpapi::debug($options);
		
		$connected = 0;
		$socket=null;

		
		
		if ( $socket = new HTTPSocket($options['host'], $options['port']) ) {
			$connected = 1;
		}
		else {
			return false;
		}

		$url = $options['url']."?";
		
		foreach ( $params as $name => $value ) {
			$concat="";
			//	If its an array concat the values
			if(is_array($value)){
				$last_item = end($value);
				foreach ( $value as $value1 ) {
					$concat.= trim(urlencode($value1));
					
					if($last_item!=$value1){
						$concat.= ",";
					}
				}
			}else{
				$concat=trim(urlencode($value));
			}
			
			// echo($name." : ".$concat."<br/>");
			
			$url .= trim(urlencode($name)).'='.$concat.'&';
			// httpapi::debug($url);
		}
		
		if($connected==1){
			$url = str_replace(' ', '%20', $url);

			$out = "GET ".$url." HTTP/1.0\r\n";
			$out .= "Host: ".$options['host']."\r\n";
			
			foreach ( $headers as $name => $value ) {
				$out .= $name.': '.$value."\r\n";
			}
			//	Headers go here		
			$out .= "\r\n";
			
			// echo("MAKING REQUEST<br/>");
			// httpapi::debug($out);
			// echo("<hr/>");			
			
			$response = $socket->send($out, 'array');

			$response = httpapi::processRespone($response);
			// httpapi::debug($response);
			return $response;
		}else{
			echo("FAIL NO CONNECTION");
			return array();
		}
		
	}
}


?>